package com.xja.seckill.order.rabbitmq;

import com.xja.seckill.order.domain.model.Order;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class RabbitMQOrderSend {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //回调函数
    final RabbitTemplate.ConfirmCallback confirmCallback=new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            /*correlationData mq插入的数据
            * ack 是否发送
            * cause 原因
            * */
            String id = correlationData.getId ();
            if (ack){
                System.out.println ("成功发送");
            }else {
                System.out.println ("处理异常");
            }
        }
    };


    public void sendOrder(Order order){
        rabbitTemplate.setConfirmCallback (confirmCallback);
        CorrelationData correlationData = new CorrelationData ();
        correlationData.setId(order.getId().toString ());
        rabbitTemplate.convertAndSend(
                "order-exchange" ,
                "createOrder",
                order,
                message -> {
                    message.getMessageProperties ().setDeliveryMode (MessageDeliveryMode.PERSISTENT);
                    message.getMessageProperties().setExpiration ("10000");
                    return message;
                },
                correlationData
        );
    }

    public void sendOrder2( ){
        rabbitTemplate.setConfirmCallback (confirmCallback);
        CorrelationData correlationData = new CorrelationData ();
        Order order = new Order ();
        order.setCode ("123456789");
        order.setType ((byte) 1);
        order.setPaymentType ((byte) 1);
        order.setStatus ((byte) 1);
        order.setCreateTime (new Date ());
        order.setIsDeleted (false);

        rabbitTemplate.convertAndSend(
                "order-exchange" ,
                "createOrder",
                order,
                message -> {
                    message.getMessageProperties ().setDeliveryMode (MessageDeliveryMode.PERSISTENT);
                    message.getMessageProperties().setExpiration ("10000");
                    return message;
                },
                correlationData
        );
    }

}
